package com.mall.service.impl;

import com.mall.exception.MallException;
import com.mall.exception.MallExceptionEnum;
import com.mall.mapper.UserMapper;
import com.mall.model.po.User;
import com.mall.service.UserService;
import com.mall.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(String userName, String password) {
        //判断用户是否存在
        User oldUser = userMapper.selectUserByUserName(userName);
        if(oldUser!=null){
            throw  new MallException(MallExceptionEnum.NAME_EXISTS);
        }
        User user = new User();
        user.setUsername(userName);
        user.setPassword(MD5Utils.getMD5Str(password));
        //添加失败处理
        int count = userMapper.insertSelective(user);
        if(count==0){
            throw  new MallException(MallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public User login(String userName, String password) {
        //查询用户信息
        User user = userMapper.selectUserByUserNameAndPassword(userName,MD5Utils.getMD5Str(password));
        if(user==null){
            throw new MallException(MallExceptionEnum.USER_ERROR_LOGIN);
        }
        return user;
    }
    @Override //更改签名
    public void updateUser(User user) {
        int count = userMapper.updateByPrimaryKeySelective(user);
        if(count==0){
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
    }
}
